package com.smart.manager.system.handler;

import cn.hutool.core.lang.Opt;
import cn.hutool.crypto.digest.DigestUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.smart.common.annotation.TaskBean;
import com.smart.common.annotation.TaskMethod;
import com.smart.manager.system.entities.enums.AppParameterType;
import com.smart.manager.system.entities.models.SystemScheduleApp;
import org.springframework.core.annotation.AnnotationUtils;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Map;
import java.util.Set;

/**
 * 调度程序扫描程序
 *
 * @author 夏绪秋
 * @date 2022-08-15
 */
public class TaskAppScanner {



    /**
     * 扫描当前系统支持的所有的计划任务程序
     */

    public static ArrayList<SystemScheduleApp> getAllSystemScheduleApp() {

        ArrayList<SystemScheduleApp> result = new ArrayList<>();
        Map<String, Object> beansWithAnnotation = SpringUtil.getBeanFactory().getBeansWithAnnotation(TaskBean.class);
        Set<String> strings = beansWithAnnotation.keySet();
        for (String beanName : strings) {
            Object bean = SpringUtil.getBean(beanName);
            Method[] methods = bean.getClass().getMethods();
            for (Method method : methods) {
                TaskMethod annotation = AnnotationUtils.findAnnotation(method, TaskMethod.class);
                Opt.ofNullable(annotation).ifPresent(x -> {
                    AppParameterType parameterType = method.getParameterCount() > 0 ? AppParameterType.WITH_PARAMETERS : AppParameterType.WITHOUT_PARAMETERS;
                    String concat = beanName.concat(method.getName()).concat(parameterType.name());
                    String token = DigestUtil.md5Hex16(concat);
                    SystemScheduleApp app = new SystemScheduleApp();
                    app.setBeanName(beanName).setMethodName(method.getName()).setParameterType(parameterType).setToken(token).setName(x.title()).setRemark(x.remark());
                    result.add(app);
                });


            }
        }
        return result;
    }





}
